package com.xiaoshuidi.cloud.framework.oss.core;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import com.xiaoshuidi.cloud.framework.oss.config.OosFileClientConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OosFileServiceImpl implements OosFileService{

    @Autowired
    OosFileClientConfig oosFileClientConfig;

    @Override
    public String oosUploadFile(File file) {
        AmazonS3 oosClient = oosFileClientConfig.oosClient();
        String pathUrl = "";
        if (file.length() == 0){
            throw new RuntimeException("文件不能为空！！！");
        }
            String fileName = file.getName();
            String remoteFilePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String dir = remoteFilePath + "/"; // 用户上传文件时指定的前缀。

            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String path = dir + UUID.randomUUID().toString().replaceAll("-","") + suffix;
            try {
                PutObjectRequest request = new PutObjectRequest(oosFileClientConfig.getBucket(), path, file);
                System.out.println("======================================上传获得节点："+oosFileClientConfig.getEndpoint()+"===============================================");
                oosClient.putObject(request);
                String url = generatePresignedUrl(path);
                System.out.println("======================================获得url："+url+"===============================================");
                pathUrl = url.substring(0, url.indexOf("?"));
                return pathUrl;
            } catch (Exception e) {
                throw new RuntimeException("文件上传失败！！！");
            } finally {
                if (oosClient != null) {
                    ((AmazonS3Client) oosClient).shutdown();
                }
            }
        }

    @Override
    public InputStream  oosDownloadFile(String url) {//处理路径
        AmazonS3 oosClient = oosFileClientConfig.oosClient();
        String head = "https://"+oosFileClientConfig.getBucket()+"."+oosFileClientConfig.getEndpoint()+"/";
        String head1 = "http://"+oosFileClientConfig.getBucket()+"."+oosFileClientConfig.getEndpoint()+"/";
        String path = url.replace(head1, "").replace(head,"");
        S3Object object = oosClient.getObject(oosFileClientConfig.getBucket(), path);

        S3ObjectInputStream InputStream = object.getObjectContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = InputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (InputStream != null) {
                    InputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        byte[] bytes = baos.toByteArray();
        return new ByteArrayInputStream(bytes);
    }


    /**
     * @Desecription: 获取文件下载地址
     */
    public String generatePresignedUrl(String fileKey) {
        GeneratePresignedUrlRequest request = new
                GeneratePresignedUrlRequest(oosFileClientConfig.getBucket(), fileKey);
        URL url = oosFileClientConfig.oosClient().generatePresignedUrl(request);
        return url.toString();
    }
}
